﻿using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;

namespace Yamfinder.Data
{
    public class ImportRepository : IImportRepository
    {
        private readonly MongoCollection<TempImportTable> _collection;
        public const string CollectionName = "TempImportTables";

        public ImportRepository(IDataSource dataSource)
        {
            _collection = dataSource.GetCollection<TempImportTable>(CollectionName);
        }

        public IQueryable<TempImportTable> Query()
        {
            return _collection.AsQueryable();
        }

        public TempImportTable Get(Guid id)
        {
            var items = _collection.AsQueryable().Where(x => x.Identifer == id);

            if (items.Count() <= 0)
            {
                return null;
            }
            return items.First();
        }

        public void Insert(TempImportTable table)
        {
            _collection.Insert(table);
        }

        public void Save(TempImportTable table)
        {
            _collection.Save(table);
        }

        public void Remove(Guid id)
        {
            var table = Get(id);

            if (table == null)
                return;

            _collection.Remove(MatchId(table.Id));
        }

        private QueryComplete MatchId(ObjectId id)
        {
            return MongoDB.Driver.Builders.Query.EQ("_id", id);
        }
    }
}